package cn.luckdou.commons.utils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.luckdou.commons.pojo.TaobaoIpReset;
import net.sf.json.JSONObject;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.method.HandlerMethod;

/**
 * Miscellaneous utilities for web applications.
 * @author L.cm
 */
public class WebUtils extends org.springframework.web.util.WebUtils {
	/**
	 * 判断是否ajax请求
	 * spring ajax 返回含有 ResponseBody 或者 RestController注解
	 * @param handlerMethod HandlerMethod
	 * @return 是否ajax请求
	 */
	public static boolean isAjax(HandlerMethod handlerMethod) {
		ResponseBody responseBody = handlerMethod.getMethodAnnotation(ResponseBody.class);
		if (null != responseBody) {
			return true;
		}
		RestController restAnnotation = handlerMethod.getBeanType().getAnnotation(RestController.class);
		if (null != restAnnotation) {
			return true;
		}
		return false;
	}
	
	/**
	 * 读取cookie
	 * @param request
	 * @param name
	 * @return
	 */
	public static String getCookieValue(HttpServletRequest request, String name) {
		Cookie cookie = getCookie(request, name);
		return cookie != null ? cookie.getValue() : null;
	}

	/**
	 * 清除 某个指定的cookie 
	 * @param response
	 * @param key
	 */
	public static void removeCookie(HttpServletResponse response, String key) {
		setCookie(response, key, null, 0);
	}

	/**
	 * 设置cookie
	 * @param response
	 * @param name
	 * @param value
	 * @param maxAgeInSeconds
	 */
	public static void setCookie(HttpServletResponse response, String name, String value, int maxAgeInSeconds) {
		Cookie cookie = new Cookie(name, value);
		cookie.setPath("/");
		cookie.setMaxAge(maxAgeInSeconds);
		cookie.setHttpOnly(true);
		response.addCookie(cookie);
	}
	public static String getIpAddr(HttpServletRequest request) {
		try {
			// 获取请求主机IP地址,如果通过代理进来，则透过防火墙获取真实IP地址
			String ip = request.getHeader("X-Forwarded-For");
			if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
				if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
					ip = request.getHeader("Proxy-Client-IP");
//                    System.out.println("getIpAddress(HttpServletRequest) - Proxy-Client-IP - String ip=" + ip);
				}
				if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
					ip = request.getHeader("WL-Proxy-Client-IP");
//                    System.out.println("getIpAddress(HttpServletRequest) - WL-Proxy-Client-IP - String ip=" + ip);
				}
				if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
					ip = request.getHeader("HTTP_CLIENT_IP");
//                    System.out.println("getIpAddress(HttpServletRequest) - HTTP_CLIENT_IP - String ip=" + ip);
				}
				if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
					ip = request.getHeader("HTTP_X_FORWARDED_FOR");
//                    System.out.println("getIpAddress(HttpServletRequest) - HTTP_X_FORWARDED_FOR - String ip=" + ip);
				}
				if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
					ip = request.getRemoteAddr();
//                    System.out.println("getIpAddress(HttpServletRequest) - getRemoteAddr - String ip=" + ip);
				}
			} else if (ip.length() > 15) {
				String[] ips = ip.split(",");
				for (int index = 0; index < ips.length; index++) {
					String strIp = (String) ips[index];
					if (!("unknown".equalsIgnoreCase(strIp))) {
						ip = strIp;
						break;
					}
				}
			}
			return ip;
		} catch (Exception e) {
			e.printStackTrace();
			return "null";
		}
	}

	/**
	 * 获取操作系统信息
	 * @param request
	 * @return
	 */
	public static String getOsInfo(HttpServletRequest request){
		String  userAgent       =   request.getHeader("User-Agent");
		String os = "";
		int i=0;
		if (userAgent.toLowerCase().indexOf("windows") >= 0 )
		{
			i=userAgent.toLowerCase().indexOf("windows");
			os = "Windows";
		} else if(userAgent.toLowerCase().indexOf("mac") >= 0)
		{
			i=userAgent.toLowerCase().indexOf("mac");
			os = "Mac";
		} else if(userAgent.toLowerCase().indexOf("x11") >= 0)
		{
			i=userAgent.toLowerCase().indexOf("x11");
			os = "Unix";
		} else if(userAgent.toLowerCase().indexOf("android") >= 0)
		{
			i=userAgent.toLowerCase().indexOf("android");
			os = "Android";
		} else if(userAgent.toLowerCase().indexOf("iphone") >= 0)
		{
			i=userAgent.toLowerCase().indexOf("iphone");
			os = "IPhone";
		}else{
			os = "UnKnown, More-Info: "+userAgent;
		}

		if (i==0){
			os = "UnKnown, More-Info: "+userAgent;
		}else{
			userAgent=userAgent.substring(i,userAgent.length());
			os=userAgent.substring(0,userAgent.indexOf(")"));
		}
		System.out.println(userAgent);
		return os ;
	}
	/**
	 * 获取浏览器及浏览器版本信息
	 * @param request
	 * @return
	 */
	public static String getBrowserInfo(HttpServletRequest request){
		String  userAgent       =   request.getHeader("User-Agent");
		String  user            =   userAgent.toLowerCase();

		String browser = "";

		if (user.contains("edge"))
		{
			browser=(userAgent.substring(userAgent.indexOf("Edge")).split(" ")[0]).replace("/", "-");
		} else if (user.contains("msie"))
		{
			String substring=userAgent.substring(userAgent.indexOf("MSIE")).split(";")[0];
			browser=substring.split(" ")[0].replace("MSIE", "IE")+"-"+substring.split(" ")[1];
		} else if (user.contains("safari") && user.contains("version"))
		{
			browser=(userAgent.substring(userAgent.indexOf("Safari")).split(" ")[0]).split("/")[0]
					+ "-" +(userAgent.substring(userAgent.indexOf("Version")).split(" ")[0]).split("/")[1];
		} else if ( user.contains("opr") || user.contains("opera"))
		{
			if(user.contains("opera")){
				browser=(userAgent.substring(userAgent.indexOf("Opera")).split(" ")[0]).split("/")[0]
						+"-"+(userAgent.substring(userAgent.indexOf("Version")).split(" ")[0]).split("/")[1];
			}else if(user.contains("opr")){
				browser=((userAgent.substring(userAgent.indexOf("OPR")).split(" ")[0]).replace("/", "-"))
						.replace("OPR", "Opera");
			}

		} else if (user.contains("chrome"))
		{
			browser=(userAgent.substring(userAgent.indexOf("Chrome")).split(" ")[0]).replace("/", "-");
		} else if ((user.indexOf("mozilla/7.0") > -1) || (user.indexOf("netscape6") != -1)  ||
				(user.indexOf("mozilla/4.7") != -1) || (user.indexOf("mozilla/4.78") != -1) ||
				(user.indexOf("mozilla/4.08") != -1) || (user.indexOf("mozilla/3") != -1) )
		{
			browser = "Netscape-?";

		} else if (user.contains("firefox"))
		{
			browser=(userAgent.substring(userAgent.indexOf("Firefox")).split(" ")[0]).replace("/", "-");
		} else if(user.contains("rv"))
		{
			String IEVersion = (userAgent.substring(userAgent.indexOf("rv")).split(" ")[0]).replace("rv:", "-");
			browser="IE" + IEVersion.substring(0,IEVersion.length() - 1);
		} else
		{
			browser = "UnKnown, More-Info: "+userAgent;
		}

		return browser ;
	}

	/**
	 * 获取IP的真实地址
	 * @param ip
	 * @return
	 */
	public static String getIpInfo2Taobao(String ip){
		String json = NetUtils.Get("http://ip.taobao.com//service/getIpInfo.php?ip=" + ip);
		JSONObject obj = new JSONObject().fromObject(json);//将json字符串转换为json对象
		TaobaoIpReset reset = (TaobaoIpReset)JSONObject.toBean(obj,TaobaoIpReset.class);
		String s="获取失败";
		if (reset.getCode()==0){
			s=reset.getData().getCountry()+"-"+
				reset.getData().getArea()+"-"+
				reset.getData().getRegion()+"-"+
				reset.getData().getCity()+"-"+
				reset.getData().getCounty()+"-"+
				reset.getData().getIsp();
		}
		return s;
	}
}
